package com.ruoyi.api.web;

import com.itmuch.lightsecurity.jwt.JwtOperator;
import com.itmuch.lightsecurity.jwt.User;
import com.ruoyi.api.base.BaseApi;
import com.ruoyi.api.po.ClientPo;
import com.ruoyi.api.utils.JwtUtils;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.api.LoginException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.weixin.domain.Client;
import com.ruoyi.weixin.service.IClientService;
import com.ruoyi.weixin.service.IWxService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api")
public class LoginApi extends BaseApi {

    @Autowired
    private JwtOperator operator;

    @Autowired
    private IWxService wxService;

    @Autowired
    private IClientService clientService;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/wechatLogin")
    public AjaxResult wechatLogin(String code, String encryptedData, String iv) throws WxErrorException {
        Client client = wxService.login(code, encryptedData, iv);
        return client(client);
    }

    @PostMapping("/emailVerified")
    public AjaxResult emailVerified(String email){
        String regStr = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile(regStr);
        Matcher m = p.matcher(email);
        if (StringUtils.isEmpty(email) || (! m.matches())){
            return error("邮箱格式错误，获取失败");
        }
        if(clientService.emailVerifi(email)){
            return success("获取成功");
        }else {
            return error("获取失败");
        }
    }

    @PostMapping("/emailLogin")
    public AjaxResult emailLogin(String email, String verifi){
        String regStr = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile(regStr);
        Matcher m = p.matcher(email);
        if (StringUtils.isEmpty(email) || (! m.matches())){
            return error("登录失败，邮箱格式错误");
        }
        Client client = clientService.emailLogin(email, verifi);
        return client(client);
    }

    @PostMapping("/padLogin")
    public AjaxResult padLogin(String name, String password) throws LoginException {
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password))return error("账号或密码错误");
        Client client = clientService.padLogin(name, password);
        return client(client);
    }

    @PostMapping("/tokenLogin")
    public AjaxResult tokenLogin(String token){
        if (StringUtils.isNotEmpty(token)){
            String id = jwtUtils.getIdByToken(token);
            if (StringUtils.isNotEmpty(id)){
                Client client = clientService.selectClientInfoById(new Client(id));
                return client(client);
            }
            return error("token无效");
        }else {
            return error("token无效");
        }
    }


    private AjaxResult client(Client client){
        if (client != null){
            ClientPo clientPo = new ClientPo(client);
            List<String> roles = new ArrayList<String>();
            roles.add(client.getGrade().getSign());
            User user = User.builder().username(client.getClientId()).roles(roles).build();
            String token = operator.generateToken(user);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("user", clientPo);
            AjaxResult ajaxResult = success("登录成功", map);
            return ajaxResult;
        }else{
            return error("未知原因");
        }
    }
}
